<script setup lang='ts'>
import { ref, reactive } from "vue"
import { storeToRefs } from "pinia"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from "element-plus"
import { Search, Minus, Plus } from '@element-plus/icons-vue'
import { useColorStore } from "@/store/common"
import { useEnumStore } from "@/store/enumeration"
import { supplierSaveOrUpdateApiPost } from "@/api/userMangement"
import useInstance from '@/hooks/useInstance';
import BlackSelect from "@/components/customSon/blackSelect.vue"

const { isIsp, supplyerType } = storeToRefs(useEnumStore())
defineOptions({
    name: 'addListAd'
})
const emit = defineEmits(['refresh','searchEdit'])
const { global } = useInstance();

const provinceData = useColorStore()
const { province, selectProvinceCity } = storeToRefs(provinceData)
const { filterData } = provinceData
const dialogBasic = ref({
    title: "新建供应商",
    visible: false,
    width: 900,
    height: 500,
    showFooter: true,
    marginTop: "10vh",
})
/** 运营商类型
 * CHINA_MOBILE("ChinaMobile", "中国移动"),
CHINA_UNICOM("ChinaUnicom", "中国联通"),
CHINA_TELECOM("ChinaTelecom", "中国电信"),
CHINA_BROADNET("ChinaBroadnet", "中国广电"),
OTHER("Other", "其他"),
 */

const supplyFormRef = ref<FormInstance>()
const addSupply = reactive<any>({
    supplierType: null,
    supplierCode: null,
    supplierName: null,
    supplierKey: null,
    extInfo: [
        {
            key: null,
            value: null
        }
    ],
    provinceCode: null,
    provinceName: null,
    cityCode: null,
    cityName: null,
    isp: null,
})

const rules = reactive<FormRules>({
    supplierKey: [
        {
            required: true,
            trigger: "blur",
            message: "请输入供应商key",
        },
        {
            pattern: /^[0-9a-zA-Z]{4,5}$/,
            trigger: "blur",
            message: "请输入四或五位数字或者英文字符",
        }
    ],
    supplierType: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择供应商类型"
        }
    ],
    supplierCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择供应商编码"
        }
    ],
    supplierName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入供应商名称"
        }
    ],
    provinceCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择所在地-省"
        }
    ],
    cityCode: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择所在地-市"
        }
    ],
    isp: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择运营商"
        }
    ]
})

const btnAdd = () => {
    addSupply.extInfo.push({
        key: null,
        value: null
    })
}
const removeDomain = (item: any) => {
    const index = addSupply.extInfo.indexOf(item)
    if (index !== -1) {
        addSupply.extInfo.splice(index, 1)
    }
}
//显示弹框
const show = (type: string, row?: any) => {
    selectProvinceCity.value = null
    global.$resetForm(supplyFormRef.value, addSupply)
    if (type === 'add') {
        dialogBasic.value.title = "新建供应商"
        addSupply.extInfo = [
            {
                key: null,
                value: null
            }
        ]
    } else {
        dialogBasic.value.title = "供应商编辑"
        global.$objCopy(addSupply, row)
        // 需要重新获取数据 用code 查询数据
        console.log(row.cityCode);

        filterData(1, null, row.provinceCode)

        const arr = JSON.parse(row.extInfo)
        if (Object.keys(arr).length > 0) {
            addSupply.extInfo = []
            Object.keys(arr).forEach(item => {
                addSupply.extInfo.push({
                    key: item,
                    value: arr[item]
                })
            })
        } else {
            addSupply.extInfo = [
                {
                    key: null,
                    value: null
                }
            ]
        }

    }
    dialogBasic.value.visible = true
}
const onClose = () => {
    selectProvinceCity.value = null

    addSupply.supplierType = null
    addSupply.supplierCode = null
    addSupply.supplierName = null
    addSupply.extInfo = [
        {
            key: null,
            value: null
        }
    ]
    addSupply.provinceCode = null
    addSupply.provinceName = null
    addSupply.cityCode = null
    addSupply.cityName = null
    addSupply.isp = null
    resetForm()
    dialogBasic.value.visible = false
}
const resetForm = () => {
    supplyFormRef.value?.resetFields()
}
const onConfirm = async () => {
    await supplyFormRef.value?.validate(async isOk => {
        if (isOk) {
            try {
                const arr: any = {}
                addSupply.extInfo && addSupply.extInfo.forEach((item: any) => {
                    if (item.key) {
                        arr[item.key] = item.value
                    }
                })
                const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
                const res = await supplierSaveOrUpdateApiPost({ ...addSupply, extInfo: newArr })
                if (res.code == 20000) {
                    ElMessage({
                        message: addSupply?.id ? "供应商编辑成功" : "供应商新增成功",
                        type: "success"
                    })
                    if(addSupply?.id){
                        emit('searchEdit')

                    }else{
                        emit('refresh')

                    }
                    onClose()
                }
            } catch (error) {
                ElMessage({
                    message: addSupply?.id ? "供应商编辑失败 请重试！" : "供应商新增失败 请重试！",
                    type: "warning"
                })
            }



        }
    })
}

const proChange = (val: any) => {
    province.value.some(item => {
        if (val == item.dictItemCode) {
            filterData(1, item.id)
            addSupply.provinceName = item.dictItemName
            addSupply.cityCode = null
            addSupply.cityName = null
            return
        }
    })

}
const proChange1 = (val: any) => {
    console.log(val);
    selectProvinceCity.value.some((item: any) => {
        if (val == item.dictItemCode) {
            addSupply.cityName = item.dictItemName
            return
        }
    })
}



defineExpose({
    show
})
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <el-form ref="supplyFormRef" :model="addSupply" :rules="rules" label-width="120px" class="demo-ruleForm"
                status-icon>

                <el-form-item label="供应商类型" prop="supplierType">
                    <BlackSelect v-model:select-value="addSupply.supplierType" :options="supplyerType"></BlackSelect>
                </el-form-item>
                <el-form-item label="供应商编码" prop="supplierCode">
                    <el-input v-model="addSupply.supplierCode" placeholder="请输入供应商编码" clearable></el-input>
                </el-form-item>
                <el-form-item label="供应商key" prop="supplierKey">
                    <el-input v-model="addSupply.supplierKey" placeholder="请输入供应商key" clearable></el-input>
                </el-form-item>
                <el-form-item label=" 供应商名称" prop="supplierName">
                    <el-input v-model="addSupply.supplierName" placeholder="请输入供应商名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="所在地-省" prop="provinceCode">
                    <el-select v-model="addSupply.provinceCode" @change="proChange" placeholder="请选择所在省份">
                        <el-option v-for="item in province" :key="item.id" :label="item.dictItemName"
                            :value="item.dictItemCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在地-市" prop="cityCode">
                    <el-select v-model="addSupply.cityCode" @change="proChange1" placeholder="请选择所在市">
                        <el-option v-for="item in selectProvinceCity" :key="item.id" :label="item.dictItemName"
                            :value="item.dictItemCode" />
                    </el-select>
                </el-form-item>
                <el-form-item label="运营商" prop="isp">
                    <el-select v-model="addSupply.isp" placeholder="请选择运营商">
                        <el-option v-for="(item, index) in isIsp" :key="item" :value="index" :label="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-for="(domain, index) in addSupply.extInfo" :key="index" :label="'信息扩展' + (index + 1)">
                    <el-row style="width: 100%;margin-bottom: 5px;" justify="space-around">
                        <el-col :span="6">
                            <el-input v-model="domain.key" placeholder="请输入value" :autosize="{ minRows: 2, maxRows: 4 }"
                                type="textarea"></el-input>
                        </el-col>
                        <el-col :span="15">
                            <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                placeholder="请输入value" clearable></el-input>
                        </el-col>
                        <el-col :span="2">
                            <el-button type="danger" style="margin-top: 12px" size="small" @click="removeDomain(domain)"
                                :icon="Minus" />
                        </el-col>
                    </el-row>
                </el-form-item>


                <el-form-item label="添加信息扩展">

                    <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 100%;" />
                </el-form-item>

            </el-form>
        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.demo-ruleForm {
    height: 480px;
    overflow: auto;
}
</style>
